package com.huohua.jobschduler.JobProcess;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huohua.jobschduler.mapper.JobMapper;
import com.huohua.jobschduler.model.po.IJob;
import com.huohua.jobschduler.model.po.Job;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class DefaultDependencyResolver extends AsyncDependencyResolver{

    private static final String INPUT_DIRECTION = "I";
    private static final String OUTPUT_DIRECTION = "O";

    @Resource
    JobMapper jobMapper;

    @Override
    protected IJob getJob(String jobId) {
        List<Job> jobs = jobMapper.selectList(
                new QueryWrapper<Job>()
                        .eq("instance_id", jobId));
        return jobs.get(0);
    }

    @Override
    protected List<IJob> getPreJobs(IJob iJob) {
        Job job = (Job) iJob;
        Set<Job> jobs = new HashSet<>();
        List<Job> events = jobMapper.selectList(
                new QueryWrapper<Job>()
                        .eq("instance_id", job.getInstanceId())
                        .eq("output_direction", "I"));
        events.forEach(event -> {
            List<Job> list = jobMapper.selectList(new QueryWrapper<Job>()
                    .eq("output_direction", "O")
                    .eq("dependency_event", event.getDependencyEvent()));
            jobs.addAll(list);
        });
        return new ArrayList<>(jobs);
    }
}
